package download.com;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;

import utils.com.FilesUtils;

public class HttpDownloader {
	private URL url = null;
	private Context context;
	
	public HttpDownloader(Context context) {
		super();
		this.context = context;
	}

	public String download(String urlStr){
		
		StringBuffer stringBuffer = new StringBuffer();
		String line = null;
		BufferedReader buffer = null;
		
		try {
			buffer = new BufferedReader(new InputStreamReader(getInputStreamFromUrl(urlStr)));
			while((line = buffer.readLine()) != null){
				stringBuffer.append(line);
			}
		} 
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		finally{
			try {
				buffer.close();
			} 
			catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}		
		return stringBuffer.toString();	
	}
	
	public int downFile(String urlStr, String path, String fileName){
		InputStream inputStream = null;
		
		FilesUtils fileUtils = new FilesUtils(context);
		if(fileUtils.isFileExist(fileName, path)){
			return 1;
		}
		else{
			try{
				inputStream = getInputStreamFromUrl(urlStr);
				File resaultFile = fileUtils.write2SDFromInput(path, fileName, inputStream);
				if(resaultFile == null){
					return -1;
				}
			}catch(Exception e){
				e.printStackTrace();
				return -1;
			}
			finally{
				try {
					inputStream.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}
		return 0;		
	}
	
	private InputStream getInputStreamFromUrl(String urlStr) throws MalformedURLException, IOException {
		// TODO Auto-generated method stub
		url = new URL(urlStr);
		HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
		InputStream inputStream = urlConn.getInputStream();
		return inputStream;
	}
}
